package org.apaydin.eksisozluk;

import org.apaydin.BaseFetcher;
import org.htmlcleaner.ContentNode;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

public class ItemFetcherImpl extends BaseFetcher implements Fetcher<EksiTopic>{

    public ItemFetcherImpl() {
        super();
    }

    @Override
    public void fetch(EksiTopic topic, int page) throws IOException, XPatherException {
        if(page <= 0){
            throw new EksiException("Page must be positive");
        }

        TagNode node = getRootTagNode(BASE_URL + topic.getHref() + "&p=" + page);

        for (TagNode n : evaluateXPath(node, "//ol[@class='eol']/li")) {
            StringBuilder text = new StringBuilder();
            List children = n.getChildren();
            for(int i = 0; i<children.size() ; i++) {
                Object nn = children.get(i);
                if(nn instanceof TagNode){
                    if(((TagNode) nn).getName().equals("br")){
                        Object nn1 = children.get(i+1);
                        if(!(nn1 instanceof TagNode && ( ((TagNode) nn1).getName().equals("div") || ((TagNode) nn1).getName().equals("br") ))){
                            text.append("\n");
                        }
                    }else if(((TagNode) nn).getName().equals("div")){
                        break;
                    }else {
                        text.append(((TagNode) nn).getText());
                    }
                }if(nn instanceof ContentNode){
                    text.append(((ContentNode) nn).getContent());
                }
            }

            EksiItem item = new EksiItem(n.getAttributeByName("value"), text.toString());
            topic.getEksiItems().addEksiItem(item);
        }

        List<TagNode> countNodes = evaluateXPath(node, "//div[@class='pagi']");
        if(countNodes.size() == 0){
            topic.getEksiItems().setItemCount(topic.getEksiItems().getItems().size());
            topic.getEksiItems().setPageCount(1);
            topic.getEksiItems().setCurrentPage(1);
        }else{
            TagNode countNode = countNodes.get(0);
//            topic.getEksiItems().setItemCount(extractItemcount(countNode.getText()));
            topic.getEksiItems().setCurrentPage(parseInt(evaluateXPath(countNode, "//select/option[@selected='selected']").get(0).getText().toString()));
            List<TagNode> as = evaluateXPath(countNode, "//span/a");
            topic.getEksiItems().setPageCount(extractPagecount(as));
        }
    }

}
